package student.aistar.day14;

import student.aistar.day10.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * IO流的工具类
 */
public class IOUtil {

    //提供一个方法可以保存任意对象
    public static <T> void writeList(List<T> list, String path){
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path))) {
            out.writeObject(list);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //提供一个方法可以读取文件中的任意对象
    //语法如果定义成了泛型类, 但是是普通方法的话, 那么这个普通方法是不需要设置成泛型的
    //如果定义成了泛型类, 并且是静态方法的话, 那么必须把这个静态方法也设置成泛型方法
    public static <T> List<T> readList(String path){
        List<T> list = null;
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(path))) {
            list = (List<T>) in.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
        Book b1 = new Book(1, "1001", "python", 100.0);
        Book b2 = new Book(2, "1002", "java", 100.0);
        List<Book>bookList = new ArrayList<>();
        bookList.add(b1);
        bookList.add(b2);

        String path = "src/student/aistar/day14/book.txt";

        //写入
        IOUtil.writeList(bookList, path);

        //读
        List<Book> list = IOUtil.readList(path);
        if(null != list && list.size() > 0){
            for(Book book : list){
                System.out.println(book);
            }
        }

    }
}
